import os

from DrissionPage import Chromium
from DrissionPage._pages.mix_tab import MixTab
from loguru import logger

import config
from lib.util import io_utils


def _fetch_versions(tab: MixTab, url: str) -> list:
    tab.get(url)

    # 查找第二个.block元素
    eles = tab.eles(".:block")
    version_block = eles[1]
    # 获取div子元素
    blocks = version_block.eles("css:>div")

    version_list = list()
    for block in blocks:
        version = block.ele("tag:h3").text
        version_tokens = version.split('.')
        if int(version_tokens[0]) < 4:
            # 小于4.0的版本丢弃
            return version_list

        platform_blocks = block.eles("css:>ul>li")
        for platform_block in platform_blocks:
            platform = platform_block.ele("tag:p").text
            if "Windows" in platform:
                file_list = platform_block.eles("css:>ul>li")
                for file in file_list:
                    if "Archive" in file.text:
                        # 只取压缩包
                        tag_a = file.ele("tag:a")
                        download_url = tag_a.attr("href")
                        file_name = tag_a.text
                        logger.debug(f"{version} {platform} {file_name} {download_url}")
                        version_list.append({"version": version, "name": file_name, "url": download_url})
    return version_list


def fetch_mongodb_versions(browser: Chromium):
    try:
        tab = browser.new_tab()

        logger.debug("获取MongoDB最新版版本列表...")
        # 获取最新版本
        latest_versions = _fetch_versions(tab, "https://www.mongodb.com/try/download/community-edition/releases")
        logger.debug(f"获取MongoDB最新版本列表结束")
        latest_file_path = os.path.join(config.base_dir, "data/mongodb-latest.json")
        io_utils.write_json(latest_file_path, {"versions": latest_versions})
        logger.debug(f"保存到最新版本数据到: {latest_file_path}")

        logger.debug("获取MongoDB历史版本列表...")
        history_versions = _fetch_versions(tab, "https://www.mongodb.com/try/download/community-edition/releases/archive")
        logger.debug(f"获取MongoDB历史版本列表结束")
        history_file_path = os.path.join(config.base_dir, "data/mongodb-history.json")
        io_utils.write_json(history_file_path, {"versions": history_versions})
        logger.debug(f"保存历史版本数据到: {history_file_path}")
    except:
        logger.exception("获取MongoDB版本列表异常")
    finally:
        tab and tab.close()
